from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED
import logging

# 配置日志
logging.basicConfig(
    filename='scheduler.log',
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 创建调度器
scheduler = BackgroundScheduler(
    jobstores={
        'default': MemoryJobStore()
    },
    executors={
        'default': ThreadPoolExecutor(20)
    },
    job_defaults={
        'coalesce': False,
        'max_instances': 3
    }
)

def job_listener(event):
    if event.exception:
        logging.error(f'任务执行出错: {event.job_id}')
        logging.error(f'错误信息: {event.exception}')
        logging.error(f'错误详情: {event.traceback}')
    else:
        logging.info(f'任务执行成功: {event.job_id}')

# 添加事件监听器
scheduler.add_listener(job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

def start_scheduler():
    """启动调度器"""
    if not scheduler.running:
        scheduler.start()
        logging.info("调度器已启动")

def shutdown_scheduler():
    """关闭调度器"""
    if scheduler.running:
        scheduler.shutdown()
        logging.info("调度器已关闭") 